package com.cloud.drore.eboss.supplier.service.impl;

import com.cloud.drore.eboos.common.base.BaseServiceImpl;
import com.cloud.drore.eboos.common.base.MyMapper;
import com.cloud.drore.eboos.common.base.ResultMessage;
import com.cloud.drore.eboos.common.entity.supplier.TicketStock;
import com.cloud.drore.eboos.exception.BusinessException;
import com.cloud.drore.eboss.supplier.entity.CombinationProductStock;
import com.cloud.drore.eboss.supplier.entity.ProductStock;
import com.cloud.drore.eboss.supplier.entity.vo.CombinationProductStockVo;
import com.cloud.drore.eboss.supplier.entity.vo.ProductUnlimitedStockVo;
import com.cloud.drore.eboss.supplier.entity.vo.TicketStockVo;
import com.cloud.drore.eboss.supplier.mapper.CombinationProductStockMapper;
import com.cloud.drore.eboss.supplier.mapper.ProductRelationMapper;
import com.cloud.drore.eboss.supplier.mapper.ProductStockMapper;
import com.cloud.drore.eboss.supplier.mapper.TicketStockMapper;
import com.cloud.drore.eboss.supplier.service.IProductStockService;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.*;

import static com.cloud.drore.eboos.common.constant.CommonConstant.STOCK_MAX_VALUE;
import static com.cloud.drore.eboos.common.constant.RedisConstant.PRODUCT_STOCK_FOR_DEALER;

/**
 * 浙江卓锐科技股份有限公司 版权所有  Copyright 2018<br>
 *
 * @Description: <br>
 * @Project: eboos <br>
 * @CreateDate: Created in 2018/3/12 15:03 <br>
 * @Author: <a href="575842778@qq.com">郑永涛</a>
 */
@Service
public class ProductStockServiceImpl extends BaseServiceImpl implements IProductStockService {

    @Autowired
    ProductStockMapper productStockMapper;
    @Autowired
    TicketStockMapper ticketStockMapper;
    @Autowired
    CombinationProductStockMapper combinationProductStockMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    ProductRelationMapper productRelationMapper;

    private static String TOTAL_INVENTORY = "TOTAL_INVENTORY";
    private static String DAILY_INVENTORY = "DAILY_INVENTORY";

    @Override
    public MyMapper getMapper() {
        return productStockMapper;
    }

    /**
     * @ClassName: ProductStockServiceImpl
     * @param productStock
     * @Return: int
     * @Decription:
     * @CreateDate: Created in 2018/3/13 17:54
     * @Author: <a href="575842778@qq.com">郑永涛</a>
     * @Modify:
     */
    @Override
    public int updateProductStockByParam(ProductStock productStock){
        return productStockMapper.updateProductStockByParam(productStock);
    }

    /**
     * @ClassName: ProductStockServiceImpl
     * @param
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage
     * @Decription: 保存到分销商库存表
     * @CreateDate: Created in 2018/3/12 18:03
     * @Author: <a href="575842778@qq.com">郑永涛</a>
     * @Modify:
     */
    @Override
    public void saveProductStock()throws BusinessException{
        //库存无限的门票产品
        List<ProductUnlimitedStockVo> unlimitedStocks = productRelationMapper.getTikcketUnlimitedStock();
        for(ProductUnlimitedStockVo unlimitedStockVo:unlimitedStocks){
            ProductStock ticketProductStock = new ProductStock();
            ticketProductStock.setInventoryType(TOTAL_INVENTORY);
            ticketProductStock.setCommonProductId(unlimitedStockVo.getCommonProductId());
            //获取分销id
            ticketProductStock.setDistributorId(unlimitedStockVo.getDistributorId());
            ticketProductStock.setEndTime(new Date());
            ticketProductStock.setStartTime(new Date());
            ticketProductStock.setInventory(STOCK_MAX_VALUE);
            productStockMapper.insert(ticketProductStock);
            Map timeAndInventyUnlimited = putTimeAndInventyToMapUnlimited(new Date(),unlimitedStockVo.getTermOfValidityEndTime());
            stringRedisTemplate.delete(unlimitedStockVo.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"");
            stringRedisTemplate.opsForHash().putAll(unlimitedStockVo.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"", timeAndInventyUnlimited);
        }
        //库存无限的组合产品
        List<ProductUnlimitedStockVo> unlimitedCombinationStocks = productRelationMapper.getCombinationUnlimitedStock();
        for(ProductUnlimitedStockVo unlimitedStockVo:unlimitedCombinationStocks){
            ProductStock combinationProductStock = new ProductStock();
            combinationProductStock.setCommonProductId(unlimitedStockVo.getCommonProductId());
            combinationProductStock.setInventoryType(TOTAL_INVENTORY);
            //获取分销id
            combinationProductStock.setDistributorId(unlimitedStockVo.getDistributorId());
            combinationProductStock.setEndTime(new Date());
            combinationProductStock.setStartTime(new Date());
            combinationProductStock.setInventory(STOCK_MAX_VALUE);
            productStockMapper.insert(combinationProductStock);
            Map timeAndInventyUnlimited = putTimeAndInventyToMapUnlimited(new Date(),unlimitedStockVo.getTermOfValidityEndTime());
            stringRedisTemplate.delete(unlimitedStockVo.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"");
            stringRedisTemplate.opsForHash().putAll(unlimitedStockVo.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"", timeAndInventyUnlimited);
        }

        List<TicketStockVo> ticketStockVos = ticketStockMapper.selectTicketStockOneToday(new TicketStock());
        //删除redis 已存储健值防止存储重复值
        for (TicketStockVo stock:ticketStockVos){
            if(stringRedisTemplate.hasKey(stock.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"")){
                stringRedisTemplate.delete(stock.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"");
            }
        }
        for (TicketStockVo stock:ticketStockVos){
            ProductStock ticketProductStock = new ProductStock();
            ticketProductStock.setInventoryType(stock.getInventoryType());
            ticketProductStock.setCommonProductId(stock.getCommonProductId());
            //获取分销id
            ticketProductStock.setDistributorId(stock.getDistributorId());

            if(TOTAL_INVENTORY.equals(stock.getInventoryType())){
                if(!DateUtils.isSameDay(stock.getStartTime(),new Date())){
                    ticketProductStock.setStartTime(DateUtils.addDays(new Date(),-1));
                    ProductStock productStockByParam = productStockMapper.findProductStockByParam(ticketProductStock);
                    if (productStockByParam!=null && productStockByParam.getInventory()!=null){
                        ticketProductStock.setInventory(productStockByParam.getInventory());
                    }else {
                        ticketProductStock.setInventory(stock.getInventory());
                    }
                    ticketProductStock.setEndTime(new Date());
                    ticketProductStock.setStartTime(new Date());
                    productStockMapper.insert(ticketProductStock);
//                    stringRedisTemplate.opsForValue().set(stock.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"", String.valueOf(stock.getInventory()));
                    continue;
                }
            }
            ticketProductStock.setInventory(stock.getInventory());
            ticketProductStock.setStartTime(new Date());
            ticketProductStock.setEndTime(new Date());
            productStockMapper.insert(ticketProductStock);
            Map timeAndInventyMap = putTimeAndInventyToMap(new Date(), stock.getEndTime(), stock.getInventory());
            stringRedisTemplate.opsForHash().putAll(stock.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"", timeAndInventyMap);
        }
        List<CombinationProductStockVo> combinationProductStockVos = combinationProductStockMapper.selectComProStockOneToday();
        //删除redis 已存储健值防止存储重复值
        for (CombinationProductStockVo combinationStock:combinationProductStockVos){
            if(stringRedisTemplate.hasKey(combinationStock.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"")){
                stringRedisTemplate.delete(combinationStock.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"");
            }
        }
        for (CombinationProductStockVo combinationStock:combinationProductStockVos){
            ProductStock comProductStock = new ProductStock();
            comProductStock.setInventoryType(combinationStock.getInventoryType());
            comProductStock.setCommonProductId(combinationStock.getCommonProductId());
            //获取分销id
            comProductStock.setDistributorId(combinationStock.getDistributorId());
            if(TOTAL_INVENTORY.equals(combinationStock.getInventoryType())){
                if(!DateUtils.isSameDay(combinationStock.getStartTime(),new Date())){
                    comProductStock.setStartTime(DateUtils.addDays(new Date(),-1));
                    ProductStock productStockByParam = productStockMapper.findProductStockByParam(comProductStock);
                    if (productStockByParam!=null && productStockByParam.getInventory()!=null){
                        comProductStock.setInventory(productStockByParam.getInventory());
                    }else {
                        comProductStock.setInventory(combinationStock.getInventory());
                    }
                    comProductStock.setStartTime(new Date());
                    comProductStock.setEndTime(new Date());
                    productStockMapper.insert(comProductStock);
//                    stringRedisTemplate.opsForValue().set(combinationStock.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"", String.valueOf(combinationStock.getInventory()));
                    continue;
                }
            }
            comProductStock.setInventory(combinationStock.getInventory());
            comProductStock.setStartTime(new Date());
            comProductStock.setEndTime(new Date());
            productStockMapper.insert(comProductStock);
            Map timeAndInventyMap = putTimeAndInventyToMap(new Date(), comProductStock.getEndTime(), comProductStock.getInventory());
            stringRedisTemplate.opsForHash().putAll(combinationStock.getProductNum()+PRODUCT_STOCK_FOR_DEALER+"", timeAndInventyMap);
        }
    }

    /**
     * @ClassName: ProductStockServiceImpl
     * @param productStock
     * @Return: com.cloud.drore.eboss.supplier.entity.ProductStock
     * @Decription: 根据条件查询产品库存信息
     * @CreateDate: Created in 2018/3/13 17:56
     * @Author: <a href="575842778@qq.com">郑永涛</a>
     * @Modify:
     */
    @Override
    public ProductStock findProductStockByParam(ProductStock productStock){
        return productStockMapper.findProductStockByParam(productStock);
    }

    /**
     * @ClassName: ProductStockServiceImpl
     * @param stocks
     * @param commonProductId
     * @param productNum
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage
     * @Decription: 保存门票每日库存
     * @CreateDate: Created in 2018/4/1 13:21
     * @Author: <a href="575842778@qq.com">郑永涛</a>
     * @Modify:
     */
    public ResultMessage saveTicketProductStocks(List<TicketStock> stocks, Long commonProductId, String productNum) throws BusinessException{
        ResultMessage rs = new ResultMessage();
        List<Long> distributorIds = productStockMapper.selectDistributorIdByCommonProductId(commonProductId);
        //删除上次存储redis数据
        stringRedisTemplate.delete(productNum+PRODUCT_STOCK_FOR_DEALER+"");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date now = new Date();
        for (TicketStock stock:stocks){
            for (Long distributorId :distributorIds){
                ProductStock ticketProductStock = new ProductStock();
                ticketProductStock.setInventoryType(stock.getInventoryType());
                ticketProductStock.setCommonProductId(commonProductId);
                ticketProductStock.setDistributorId(distributorId);
                ticketProductStock.setInventory(stock.getInventory());
                ticketProductStock.setStartTime(new Date());
                ticketProductStock.setEndTime(new Date());
                productStockMapper.insert(ticketProductStock);
            }
            Map timeAndInventyMap = putTimeAndInventyToMap(stock.getStartTime(), stock.getEndTime(), stock.getInventory());
            stringRedisTemplate.opsForHash().putAll(productNum+PRODUCT_STOCK_FOR_DEALER+"", timeAndInventyMap);
        }
        rs.setMessage("保存成功！");
        return rs;
    }


    public ResultMessage saveCombinationProductStocks(List<CombinationProductStock> stocks, Long commonProductId, String productNum) throws BusinessException{
        ResultMessage rs = new ResultMessage();
        List<Long> distributorIds = productStockMapper.selectDistributorIdByCommonProductId(commonProductId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date now = new Date();
        //删除上次存储redis数据
        stringRedisTemplate.delete(productNum+PRODUCT_STOCK_FOR_DEALER+"");
        for (CombinationProductStock stock:stocks){
            for (Long distributorId :distributorIds){
                ProductStock productStock = new ProductStock();
                productStock.setCommonProductId(commonProductId);
                productStock.setInventoryType(stock.getInventoryType());
                productStock.setDistributorId(distributorId);
                productStock.setInventory(stock.getInventory());
                productStock.setStartTime(new Date());
                productStock.setEndTime(new Date());
                productStockMapper.insert(productStock);
            }
            Map timeAndInventyMap = putTimeAndInventyToMap(stock.getStartTime(), stock.getEndTime(), stock.getInventory());
            stringRedisTemplate.opsForHash().putAll(productNum+PRODUCT_STOCK_FOR_DEALER+"", timeAndInventyMap);
        }
        rs.setMessage("保存成功！");
        return rs;
    }

    /**
     * @ClassName: ProductStockServiceImpl
     * @param commonProductId
     * @param productNum
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage
     * @Decription: 保存无限制库存
     * @CreateDate: Created in 2018/4/1 13:20
     * @Author: <a href="575842778@qq.com">郑永涛</a>
     * @Modify:
     */
    public ResultMessage saveUnlimitedProductStocks(Long commonProductId,String productNum,Date startTime,Date endTime){
        ResultMessage rs = new ResultMessage();
        //获取分销id
        List<Long> distributorIds = productStockMapper.selectDistributorIdByCommonProductId(commonProductId);
        //删除上次存储redis数据
        stringRedisTemplate.delete(productNum+PRODUCT_STOCK_FOR_DEALER+"");
        for (Long distributorId :distributorIds){
            ProductStock ticketProductStock = new ProductStock();
            ticketProductStock.setInventoryType(TOTAL_INVENTORY);
            ticketProductStock.setCommonProductId(commonProductId);
            ticketProductStock.setDistributorId(distributorId);
            ticketProductStock.setEndTime(new Date());
            ticketProductStock.setStartTime(new Date());
            ticketProductStock.setInventory(STOCK_MAX_VALUE);
            productStockMapper.insert(ticketProductStock);
        }
        Map timeAndInventyMap = putTimeAndInventyToMapUnlimited(startTime,endTime);
        stringRedisTemplate.opsForHash().putAll(productNum+PRODUCT_STOCK_FOR_DEALER+"", timeAndInventyMap);
        rs.setMessage("保存成功！");
        return rs;
    }


    /**
     * @ClassName: ProductStockServiceImpl
     * @param stocks
     * @param commonProductId
     * @param productNum
     * @Return: com.cloud.drore.eboos.common.base.ResultMessage
     * @Decription:
     * @CreateDate: Created in 2018/4/11 15:55
     * @Author: <a href="575842778@qq.com">郑永涛</a>
     * @Modify:
     */
    public ResultMessage saveTicketProductStocksDealer(List<TicketStock> stocks, Long commonProductId, String productNum) throws BusinessException{
        ResultMessage rs = new ResultMessage();
        List<Long> distributorIds = productStockMapper.selectDistributorIdByCommonProductId(commonProductId);
        Date now = new Date();
        for (TicketStock stock:stocks){
            if(stock.getStartTime().getTime()<now.getTime() && stock.getEndTime().getTime()>now.getTime()){
                for (Long distributorId :distributorIds){
                    ProductStock ticketProductStock = new ProductStock();
                    ticketProductStock.setInventoryType(stock.getInventoryType());
                    ticketProductStock.setDistributorId(distributorId);
                    ticketProductStock.setCommonProductId(commonProductId);
                    ticketProductStock.setInventory(stock.getInventory());
                    ticketProductStock.setStartTime(new Date());
                    ticketProductStock.setEndTime(new Date());
                    productStockMapper.insert(ticketProductStock);
                }
                Map timeAndInventyMap = putTimeAndInventyToMap(new Date(), stock.getEndTime(), stock.getInventory());
                stringRedisTemplate.delete(productNum+PRODUCT_STOCK_FOR_DEALER+"");
                stringRedisTemplate.opsForHash().putAll(productNum+PRODUCT_STOCK_FOR_DEALER+"", timeAndInventyMap);
            }
        }
        rs.setMessage("保存成功！");
        return rs;
    }

    /**
     * @ClassName: ProductStockServiceImpl
     * @param startTime
     * @param endTime
     * @param inventory
     * @Return: java.util.Map
     * @Decription:
     * @CreateDate: Created in 2018/4/11 17:26
     * @Author: <a href="575842778@qq.com">郑永涛</a>
     * @Modify:
     */
    Map putTimeAndInventyToMap(Date startTime,Date endTime,int inventory){
        HashMap<Object, Object> dateAndStock = new HashMap<>();
        Date nowDate = new Date();
        SimpleDateFormat sdfYearMonthDay = new SimpleDateFormat("yyyy-MM-dd");
        if(nowDate.getTime() > startTime.getTime()){
            startTime = nowDate;
        }
        if((startTime.getTime()-nowDate.getTime())/(24*60*60*1000) > 60){
            return dateAndStock;
        }
        if((endTime.getTime()-nowDate.getTime())/(24*60*60*1000) > 60){
            endTime = Date.from(nowDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().plusDays(60).atStartOfDay(ZoneId.systemDefault()).toInstant());
        }
        for(;startTime.getTime()<=endTime.getTime();
        startTime = Date.from(startTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant())){
            dateAndStock.put(sdfYearMonthDay.format(startTime),String.valueOf(inventory));
        }
        return dateAndStock;
    }


    /**
     * @ClassName: ProductStockServiceImpl
     * @param
     * @Return: java.util.Map
     * @Decription:
     * @CreateDate: Created in 2018/4/11 17:45
     * @Author: <a href="575842778@qq.com">郑永涛</a>
     * @Modify:
     */
    Map putTimeAndInventyToMapUnlimited(Date startTime,Date endTime){
        HashMap<Object, Object> dateAndStock = new HashMap<>();
        SimpleDateFormat sdfYearMonthDay = new SimpleDateFormat("yyyy-MM-dd");
        Date nowDate = new Date();
        if(nowDate.getTime() > startTime.getTime()){
            startTime = nowDate;
        }
        if((endTime.getTime()-nowDate.getTime())/(24*60*60*1000) > 60){
            endTime = Date.from(nowDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().plusDays(60).atStartOfDay(ZoneId.systemDefault()).toInstant());
        }
        for(;startTime.getTime()<=endTime.getTime();
            startTime = Date.from(startTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant())){
            dateAndStock.put(sdfYearMonthDay.format(startTime),String.valueOf(STOCK_MAX_VALUE));
        }
        return dateAndStock;
    }



}